<?php
namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\Db;

/**
 * 评论
 * @author 40215
 *
 */
class Comment extends Backend{
    
    public function _initialize(){
        parent::_initialize();
        
        $this->model = model('comment');
    }
    
    public function index(){
        //设置过滤方法
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->model
            ->where($where)
            ->where(['is_del'=>0])
            ->order($sort, $order)
            ->count();
            
            $list = $this->model
            ->where($where)
            ->where(['is_del'=>0])
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
            $result = array("total" => $total, "rows" => $list);
            
            return json($result);
        }
        return $this->view->fetch();
    }
    
    public function get(){
        $result = $this->model->where(['is_del'=>0])->order("id DESC")->limit(10)->select();
        
        foreach ($result as &$v){
            $v['nick'] = subtext($v['nick'], 4);
            $v['createtime'] = date('Y-m-d', $v['addtime']);
            $v['detail'] = subtext($v['content']);
            $v['url'] = url("/admin/user/comment/view/ids/{$v['id']}");
        }
        
        return json($result);
    }
    
    public function view($ids = null){
        $row = $this->model->get($ids);
        if (!$row) $this->error(__('No Results were found'));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    public function del($ids = null){
        if($ids){
            $pk = $this->model->getPk();
            
            Db::startTrans();
            try{
                $this->model->where($pk, 'IN', $ids)->update(['is_del'=>1]);
                Db::commit();
                $this->success();
            } catch (\think\exception\PDOException $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
}